from rest_framework.permissions import BasePermission, SAFE_METHODS

class IsOwerOrReadOnly(BasePermission):
  message = 'You must be the owner to update.'

  def safe_methods_or_owner(self, request, func):
    if request.method in SAFE_METHODS:
      return True
    return func()

  # 早于 def perform_create(...) 执行
  def has_permission(self, request, view):
    print('has_permission', request.user.is_authenticated)
    return self.safe_methods_or_owner(request, lambda: request.user.is_authenticated)
  
  # 晚于 def perform_create(...) 执行
  def has_object_permission(self, request, view, obj):
    return self.safe_methods_or_owner(request, lambda: obj.author == request.user)
